from notemgr import notemgr
from blockmgr import blockmgr
from tagmgr import tagmgr
import json
def dumps(state, data=''):
    return json.dumps([state, data])

def list_note(request, count=-1):
    """return @count notes"""
    ns = [{'id':n.id, 'title':n.title} for n in notemgr.get_all()]
    request.respond(dumps(200, ns))
    request.done(200)

def add_note(request, title):
    id = notemgr.add(title)
    request.respond(dumps(200, {'id': id, 'title': title}))
    request.done(200)

def remove_note(request, id):
    note = None
    try:
        if not id.isdigit():
            raise TypeError, 'id(%s) is not a digit' % id
        note = notemgr.get(id)
        for b in blockmgr.get_by_note_id(id):
            tagmgr.detach_all(b.id);
            blockmgr.remove(b.id)
        notemgr.remove(id)
    except TypeError, e:
        request.respond(dumps(500, repr(e)))
    else:
        request.respond(dumps(200, note.serialize()))
    request.done(200)

def rename_note(request, id, title):
    try:
        if not id.isdigit():
            raise TypeError, 'id(%s) is not a digit' % id
        notemgr.rename(id, title)
    except TypeError, e:
        request.respond(dumps(500, repr(e) ))
    else:
        request.respond(dumps(200, {'id': id, 'title': title}))
    request.done(200)



